package com.csq.aop;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author ercai
 * @date 2019/7/25 - 14:09
 */
public class UserMapperInterceptor implements MethodInterceptor {

    //1.代理的目标
    private Object targetObject;

    public UserMapperInterceptor(Object object){
        this.targetObject = object;
    }

    //2.生成代理类
    public Object createProxy(){

        //字节码增强技术
        Enhancer enhancer = new Enhancer();
        //设置代理类的父类是目标类
         enhancer.setSuperclass(targetObject.getClass());
        //设置回调
        enhancer.setCallback(this);
        return enhancer.create();
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        if("insert".equals(method.getName())){
            System.out.println("开启事务");
            try {
                method.invoke(targetObject, objects);
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("事务回滚");
            }
            System.out.println("提交事务");
        }
        return null;
    }
}
